﻿/* AgileFx Version 1.0
 * An open-source framework for rapid development of applications and services using Microsoft.net
 * Developed by: AgileHead
 * Website: www.agilefx.org
 * This component is licensed under the terms of the Apache 2.0 License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Reflection;

namespace AgileFx.EF
{
    public class ExpressionUtil
    {
        public static string GetPropertyName(LambdaExpression expression)
        {
            if (null == expression) return null;

            //if (expression.Body
            string rhs = expression.Body.ToString();
            int dot = rhs.IndexOf('.');
            var result = (dot != -1) ? rhs.Substring(dot + 1) : null;
            return result;
        }

        //Gets the property refered to by the Expression
        public static PropertyInfo GetProperty(LambdaExpression expression, object obj)
        {
            var propName = GetPropertyName(expression);
            return propName.Empty() ? null : obj.GetType().GetProperty(propName);
        }

        //Gets the property value refered to by the Expression
        public static object GetPropertyValue(LambdaExpression expression, object container)
        {
            var prop = GetProperty(expression, container);
            return (null == prop) ? container : prop.GetValue(container, null);
        }
    }
}
